<template>
  <view class="arrears-duration-stats-container">
    <z-paging 
      ref="paging" 
      v-model="dataList" 
      @query="queryList"
      :auto="false"
      :refresher-enabled="true"
      :loading-more-enabled="true"
      :empty-view-text="'暂无数据'"
      class="list-paging"
    >
      <template #top>
        <!-- 页面标题 -->
        <view class="page-header">
          <view class="header-title">欠费时长统计</view>
        </view>
        
        <!-- 筛选区域 -->
        <view class="filter-section">
          <view class="filter-row">
            <view class="filter-item">
              <text class="filter-label">统计周期：</text>
              <picker mode="selector" :value="filters.periodIndex" :range="periodOptions" @change="onPeriodChange">
                <view class="date-picker">
                  <text>{{ filters.periodIndex >= 0 ? periodOptions[filters.periodIndex] : '请选择' }}</text>
                  <up-icon name="arrow-down" size="14"></up-icon>
                </view>
              </picker>
            </view>
            
            <view class="filter-item">
              <text class="filter-label">停车场：</text>
              <picker :value="filters.parkingLotIndex" :range="parkingLotOptions" @change="onParkingLotChange">
                <view class="date-picker">
                  <text>{{ filters.parkingLotIndex >= 0 ? parkingLotOptions[filters.parkingLotIndex] : '全部' }}</text>
                  <up-icon name="arrow-down" size="14"></up-icon>
                </view>
              </picker>
            </view>
          </view>
          
          <view class="filter-row">
            <view class="filter-item">
              <text class="filter-label">欠费时长：</text>
              <picker :value="filters.durationIndex" :range="durationOptions" @change="onDurationChange">
                <view class="date-picker">
                  <text>{{ filters.durationIndex >= 0 ? durationOptions[filters.durationIndex] : '全部' }}</text>
                  <up-icon name="arrow-down" size="14"></up-icon>
                </view>
              </picker>
            </view>
          </view>
          
          <view class="filter-actions">
            <button class="search-btn" @click="searchData">查询</button>
            <button class="reset-btn" @click="resetFilters">重置</button>
          </view>
        </view>
        
        <!-- 统计摘要 -->
        <view class="summary-section">
          <view class="summary-card">
            <view class="summary-title">订单总数</view>
            <view class="summary-value">{{ summary.totalOrders }}</view>
          </view>
          <view class="summary-card">
            <view class="summary-title">欠费总额</view>
            <view class="summary-value">{{ summary.totalAmount }}元</view>
          </view>
          <view class="summary-card">
            <view class="summary-title">平均欠费时长</view>
            <view class="summary-value">{{ summary.avgDuration }}天</view>
          </view>
        </view>
        
        <!-- 列表表头 -->
        <view class="list-header">
          <text class="list-cell">欠费时长</text>
          <text class="list-cell">订单数量</text>
          <text class="list-cell">占比</text>
          <text class="list-cell">欠费总额</text>
          <text class="list-cell">平均欠费</text>
        </view>
      </template>
      
      <!-- 列表内容 -->
      <view v-for="(item, index) in dataList" :key="index" class="list-row" @click="showDetail(item)">
        <text class="list-cell">{{ item.durationText }}</text>
        <text class="list-cell">{{ item.orderCount }}</text>
        <text class="list-cell">{{ item.percentage }}%</text>
        <text class="list-cell">{{ item.totalAmount }}元</text>
        <text class="list-cell">{{ item.averageAmount }}元</text>
      </view>
    </z-paging>
    
    <!-- 详情弹窗 -->
    <view class="detail-modal" v-if="showDetailModal">
      <view class="detail-content">
        <view class="detail-header">
          <text class="detail-title">详情信息</text>
          <text class="close-btn" @click="showDetailModal = false">×</text>
        </view>
        
        <view class="detail-body" v-if="currentDetail">
          <view class="detail-item">
            <text class="detail-label">欠费时长：</text>
            <text class="detail-value">{{ currentDetail.durationText }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">统计周期：</text>
            <text class="detail-value">{{ periodOptions[filters.periodIndex] }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">停车场：</text>
            <text class="detail-value">{{ currentDetail.parkingLot }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">订单数量：</text>
            <text class="detail-value">{{ currentDetail.orderCount }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">占比：</text>
            <text class="detail-value">{{ currentDetail.percentage }}%</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">欠费总额：</text>
            <text class="detail-value">{{ currentDetail.totalAmount }}元</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">平均欠费：</text>
            <text class="detail-value">{{ currentDetail.averageAmount }}元</text>
          </view>
          
          <view class="detail-item" v-if="currentDetail.durationDays > 0">
            <text class="detail-label">平均欠费天数：</text>
            <text class="detail-value">{{ currentDetail.durationDays }}天</text>
          </view>
          
          <view class="detail-item" v-if="currentDetail.maxAmount">
            <text class="detail-label">最高欠费：</text>
            <text class="detail-value">{{ currentDetail.maxAmount }}元</text>
          </view>
          
          <view class="detail-item" v-if="currentDetail.minAmount">
            <text class="detail-label">最低欠费：</text>
            <text class="detail-value">{{ currentDetail.minAmount }}元</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'

// 筛选条件
const filters = reactive({
  periodIndex: 0,
  parkingLotIndex: -1,
  durationIndex: -1
})

// 统计周期选项
const periodOptions = [
  '日统计',
  '月统计',
  '年统计'
]

// 停车场选项
const parkingLotOptions = [
  '全部',
  'A区停车场',
  'B区停车场',
  'C区停车场',
  'D区停车场'
]

// 欠费时长选项
const durationOptions = [
  '全部',
  '1天以内',
  '1-7天',
  '7-30天',
  '30-90天',
  '90天以上'
]

// 列表数据
const dataList = ref([])
const paging = ref(null)

// 统计摘要数据
const summary = reactive({
  totalOrders: 0,
  totalAmount: '0.00',
  avgDuration: '0'
})

// 详情弹窗
const showDetailModal = ref(false)
const currentDetail = ref(null)

// 统计周期选择处理
const onPeriodChange = (e) => {
  filters.periodIndex = parseInt(e.detail.value)
}

// 停车场选择处理
const onParkingLotChange = (e) => {
  filters.parkingLotIndex = parseInt(e.detail.value)
}

// 欠费时长选择处理
const onDurationChange = (e) => {
  filters.durationIndex = parseInt(e.detail.value)
}

// 查询数据
const searchData = () => {
  if (paging.value) {
    paging.value.reload()
  }
}

// 重置筛选条件
const resetFilters = () => {
  filters.periodIndex = 0
  filters.parkingLotIndex = -1
  filters.durationIndex = -1
  
  nextTick(() => {
    if (paging.value) {
      paging.value.reload()
    }
  })
}

// 查询列表数据
const queryList = (pageNo, pageSize) => {
  // 模拟请求延迟
  setTimeout(() => {
    // 生成模拟数据
    const data = generateMockData(pageNo, pageSize)
    paging.value.complete(data)
    
    // 更新统计摘要
    updateSummary()
  }, 500)
}

// 更新统计摘要
const updateSummary = () => {
  // 模拟总订单数
  summary.totalOrders = Math.floor(Math.random() * 5000) + 1000
  
  // 模拟总欠费金额
  const totalAmount = Math.floor(Math.random() * 100000) + 10000
  summary.totalAmount = (totalAmount / 100).toFixed(2)
  
  // 模拟平均欠费时长
  summary.avgDuration = Math.floor(Math.random() * 30) + 5
}

// 生成模拟数据
const generateMockData = (pageNo, pageSize) => {
  const data = []
  
  // 定义欠费时长类型
  const durationTypes = [
    { text: '1天以内', minDays: 0, maxDays: 1 },
    { text: '1-7天', minDays: 1, maxDays: 7 },
    { text: '7-30天', minDays: 7, maxDays: 30 },
    { text: '30-90天', minDays: 30, maxDays: 90 },
    { text: '90天以上', minDays: 90, maxDays: 365 }
  ]
  
  // 停车场列表
  const parkingLots = parkingLotOptions.slice(1) // 排除"全部"选项
  
  // 计算总订单数（用于计算占比）
  const totalOrders = Math.floor(Math.random() * 5000) + 1000
  let remainingOrders = totalOrders
  
  // 根据筛选条件确定要生成的欠费时长类型
  let typesToGenerate = []
  if (filters.durationIndex <= 0) {
    // 全部类型
    typesToGenerate = [...durationTypes]
  } else {
    // 选择了特定类型
    typesToGenerate = [durationTypes[filters.durationIndex - 1]]
  }
  
  // 生成随机数据
  for (let i = 0; i < typesToGenerate.length; i++) {
    const currentType = typesToGenerate[i]
    
    // 根据欠费时长类型确定要生成的订单数量
    let orderCount
    if (typesToGenerate.length === 1) {
      // 如果只选择了一种类型，则使用全部订单数
      orderCount = totalOrders
    } else if (i === typesToGenerate.length - 1) {
      // 最后一个类型使用剩余订单数
      orderCount = remainingOrders
    } else {
      // 根据欠费时长类型设置不同的订单数量分布
      let percentage
      if (currentType.text === '1天以内') {
        percentage = Math.random() * 0.2 + 0.3 // 30%-50%
      } else if (currentType.text === '1-7天') {
        percentage = Math.random() * 0.15 + 0.2 // 20%-35%
      } else if (currentType.text === '7-30天') {
        percentage = Math.random() * 0.1 + 0.1 // 10%-20%
      } else if (currentType.text === '30-90天') {
        percentage = Math.random() * 0.05 + 0.05 // 5%-10%
      } else { // 90天以上
        percentage = Math.random() * 0.05 + 0.01 // 1%-6%
      }
      orderCount = Math.floor(totalOrders * percentage)
      remainingOrders -= orderCount
    }
    
    // 计算占比
    const percentage = ((orderCount / totalOrders) * 100).toFixed(2)
    
    // 生成欠费金额（根据欠费时长类型设置不同的金额范围）
    let totalAmount = 0
    let averageAmount = 0
    let maxAmount = 0
    let minAmount = 0
    let durationDays = 0
    
    if (currentType.text === '1天以内') {
      averageAmount = Math.floor(Math.random() * 20) + 10 // 10-30元
      durationDays = Math.random() * 0.9 + 0.1 // 0.1-1天
    } else if (currentType.text === '1-7天') {
      averageAmount = Math.floor(Math.random() * 30) + 20 // 20-50元
      durationDays = Math.random() * 6 + 1 // 1-7天
    } else if (currentType.text === '7-30天') {
      averageAmount = Math.floor(Math.random() * 50) + 40 // 40-90元
      durationDays = Math.random() * 23 + 7 // 7-30天
    } else if (currentType.text === '30-90天') {
      averageAmount = Math.floor(Math.random() * 100) + 80 // 80-180元
      durationDays = Math.random() * 60 + 30 // 30-90天
    } else { // 90天以上
      averageAmount = Math.floor(Math.random() * 200) + 150 // 150-350元
      durationDays = Math.random() * 275 + 90 // 90-365天
    }
    
    totalAmount = (averageAmount * orderCount).toFixed(2)
    averageAmount = averageAmount.toFixed(2)
    maxAmount = (averageAmount * (1 + Math.random() * 0.5)).toFixed(2) // 最高上浮50%
    minAmount = (averageAmount * (1 - Math.random() * 0.3)).toFixed(2) // 最低下浮30%
    
    // 随机选择停车场
    const selectedParkingLotIndex = filters.parkingLotIndex > 0 
      ? filters.parkingLotIndex - 1 
      : Math.floor(Math.random() * parkingLots.length)
    const parkingLot = parkingLots[selectedParkingLotIndex]
    
    // 添加数据
    data.push({
      id: i + 1,
      durationText: currentType.text,
      durationDays: Math.round(durationDays),
      orderCount,
      percentage,
      totalAmount,
      averageAmount,
      maxAmount,
      minAmount,
      parkingLot
    })
  }
  
  return data
}

// 显示详情
const showDetail = (item) => {
  currentDetail.value = item
  showDetailModal.value = true
}

// 页面加载
onMounted(() => {
  // 页面挂载时获取数据
  nextTick(() => {
    if (paging.value) {
      paging.value.reload()
    }
  })
})
</script>

<style lang="scss" scoped>
.arrears-duration-stats-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.list-paging {
  flex: 1;
  height: 100%;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx 30rpx 30rpx;
  color: white;
  
  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
  }
}

.filter-section {
  background: white;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  
  .filter-row {
    display: flex;
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .filter-item {
    flex: 1;
    margin-right: 20rpx;
    
    &:last-child {
      margin-right: 0;
    }
    
    &.full-width {
      flex: none;
      width: 100%;
      margin-right: 0;
    }
  }
  
  .filter-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
    display: block;
  }
  
  .date-picker,
  .picker-input {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 10rpx;
    background: #fafafa;
    font-size: 26rpx;
    color: #666;
  }
  
  .filter-actions {
    display: flex;
    gap: 20rpx;
    margin-top: 30rpx;
  }
  
  .search-btn,
  .reset-btn {
    flex: 1;
    padding: 20rpx;
    border-radius: 10rpx;
    font-size: 28rpx;
    border: none;
  }
  
  .search-btn {
    background: #1890FF;
    color: white;
  }
  
  .reset-btn {
    background: #f0f0f0;
    color: #666;
  }
}

.summary-section {
  display: flex;
  justify-content: space-between;
  margin: 0 20rpx 20rpx;
  
  .summary-card {
    flex: 1;
    background: white;
    border-radius: 10rpx;
    padding: 20rpx;
    margin: 0 10rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    text-align: center;
    
    &:first-child {
      margin-left: 0;
    }
    
    &:last-child {
      margin-right: 0;
    }
    
    .summary-title {
      font-size: 24rpx;
      color: #666;
      margin-bottom: 10rpx;
    }
    
    .summary-value {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
    }
  }
}

.list-header {
  display: flex;
  background: #f0f0f0;
  padding: 20rpx;
  margin: 0 20rpx;
  border-radius: 10rpx 10rpx 0 0;
  font-size: 26rpx;
  font-weight: bold;
  color: #333;
}

.list-row {
  display: flex;
  background: white;
  padding: 20rpx;
  margin: 0 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
  font-size: 26rpx;
  color: #666;
  
  &:last-child {
    border-radius: 0 0 10rpx 10rpx;
    margin-bottom: 20rpx;
  }
}

.list-cell {
  flex: 1;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.detail-content {
  width: 80%;
  max-height: 80%;
  background: white;
  border-radius: 20rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: #f5f5f5;
  border-bottom: 2rpx solid #e0e0e0;
  
  .detail-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .close-btn {
    font-size: 40rpx;
    color: #999;
    line-height: 1;
  }
}

.detail-body {
  padding: 30rpx;
  overflow-y: auto;
}

.detail-item {
  display: flex;
  margin-bottom: 20rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .detail-label {
    width: 200rpx;
    font-size: 28rpx;
    color: #666;
  }
  
  .detail-value {
    flex: 1;
    font-size: 28rpx;
    color: #333;
  }
}
</style>